package cn.yu_lu.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 数据格式转换工具类
 * 
 * @author zhang
 *
 */
public class ConvertUtil {
	
	/**
	 * 字符串编码转换
	 * @param str 待转换字符集字符串
	 * @param fromEncoding 字符串原始编码
	 * @param toEncoding 转换的目标编码
	 * @return 转化编码后的字符串,当待转换字符集字符串，源字符集，目标字符集任何一个为空字符串时返回null
	 * @throws UnsupportedEncodingException 当使用不支持的字符集时抛出
	 */
	public static String convertEncoding(String str,String fromEncoding,String toEncoding) throws UnsupportedEncodingException{
		if(JudgeUtil.hasBlank(str,fromEncoding,toEncoding)) return null;
		return new String(str.getBytes(fromEncoding),toEncoding);
	}
	
	/**
	 * 将字符串从utf-8编码转换为iso8859-1编码
	 * @param str 待转换字符集字符串
	 * @return 转化编码后的字符串,当传入空字符串时返回null
	 */
	public static String utf2iso(String str){
		if(JudgeUtil.isBlank(str)) return null;
		try {
			return convertEncoding(str,"UTF-8","ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}
	
	/**
	 * 将字符串从iso8859-1编码转换为utf-8编码
	 * @param str 待转换字符集字符串
	 * @return 转化编码后的字符串,当传入空字符串时返回null
	 */
	public static String iso2utf(String str){
		if(JudgeUtil.isBlank(str)) return null;
		try {
			return convertEncoding(str,"ISO8859-1","UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}

	/**
	 * 按照指定的格式字符串将指定的日期对象格式化为字符串
	 * @param date 待格式化日期
	 * @param formatStr 格式化字符串
	 * @return 传入的Date对象为空或格式化字符串为空白字符串返回null,否则使用SimpleDateFormat按传入的格式化字符串格式化日期对象
	 */
	public static String formatDate(Date date, String formatStr) {
		if (date == null || JudgeUtil.isBlank(formatStr)) return null;
		SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
		return dateFormat.format(date);
	}

	/**
	 * 按照指定的日期格式将日期字符串解析为日期对象
	 * @param dateStr 日期字符串
	 * @param formatStr 格式字符串
	 * @return 传入的日期字符串或格式字符串为空白字符串时返回null,否则使用SimpleDateFormat解析日期字符串
	 * @throws ParseException 日期字符串与格式字符串不匹配时抛出解析异常
	 */
	public static Date parseDate(String dateStr, String formatStr){
		if (JudgeUtil.hasBlank(dateStr, formatStr)) return null;
		SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
		try {
			return dateFormat.parse(dateStr);
		} catch (ParseException e) {
			throw new IllegalArgumentException();
		}
	}

	//16进制使用的字符数组
	private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd','e', 'f' };
	/**
	 * 将字节数组转化为16进制字符串
	 * @param data 待转换字节数组
	 * @return 转后后的16进制字符串,当传入空字节数组是返回null
	 */
	public static String toHex(byte[] data) {
		if (data == null || data.length == 0) return null;
		final int l = data.length;
		final char[] out = new char[l << 1];
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = HEX_CHARS[(0xF0 & data[i]) >>> 4];
			out[j++] = HEX_CHARS[0x0F & data[i]];
		}
		return new String(out);
	}

	/**
	 * 将16进制字符串转换为字节数组
	 * @param hexStr 16进制字符串
	 * @return 返回转换后的字节数组，当传入空字符串时返回null
	 * @throws IllegalArgumentException 当传入不符合规范的字符串时抛出
	 */
	public static byte[] hex2Bytes(String hexStr){
		if(JudgeUtil.isBlank(hexStr)) return null;
		int length=hexStr.length();
		if(length%2!=0) throw new IllegalArgumentException();
		byte[] res = new byte[length/2];        
        for(int i=0; i<res.length; i++){  
            res[i] = (byte) (Integer.parseInt(hexStr.substring(2*i,2*i+2), 16));  
        }  
        return res; 
	}
	
	/**
	 * 将指定的字符串进行urlencode(utf-8)
	 * @param str 待转换字符串
	 * @return urlencode后的字符串,当传入空字符串时返回null
	 */
	public static String urlEncode(String str) {
		if (JudgeUtil.isBlank(str)) return null;
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}

	/**
	 * 将指定的字符串进行urldecode(utf-8)
	 * @param str 待转换字符串
	 * @return urldecode后的字符串,当传入空字符串时返回null
	 */
	public static String urlDecode(String str) {
		if (JudgeUtil.isBlank(str)) return null;
		try {
			return URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}

	//base64编码使用的字符数组
	private static final char[] BASE64_ENCODE_CHARS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
			'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
			'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
			'3', '4', '5', '6', '7', '8', '9', '+', '/' };
	/**
	 * 将指定的字符串进行base64编码
	 * @param str 待编码字符串
	 * @return base64编码后的字符串,当传入空字符串时返回null
	 */
	public static String base64Encode(String str) {
		if (JudgeUtil.isBlank(str)) return null;
		String data=utf2iso(str);
		StringBuilder strBuilder = new StringBuilder();
		int i = 0, length = data.length();
		while (i < length) {
			int c1 = data.codePointAt(i++) & 0xff;
			if (i == length) {
				strBuilder.append(BASE64_ENCODE_CHARS[c1 >> 2]);
				strBuilder.append(BASE64_ENCODE_CHARS[(c1 & 0x3) << 4]);
				strBuilder.append("==");
				break;
			}
			int c2 = data.codePointAt(i++);
			if (i == length) {
				strBuilder.append(BASE64_ENCODE_CHARS[c1 >> 2]);
				strBuilder.append(BASE64_ENCODE_CHARS[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)]);
				strBuilder.append(BASE64_ENCODE_CHARS[(c2 & 0xF) << 2]);
				strBuilder.append("=");
				break;
			}
			int c3 = data.codePointAt(i++);
			strBuilder.append(BASE64_ENCODE_CHARS[c1 >> 2]);
			strBuilder.append(BASE64_ENCODE_CHARS[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)]);
			strBuilder.append(BASE64_ENCODE_CHARS[((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)]);
			strBuilder.append(BASE64_ENCODE_CHARS[c3 & 0x3F]);
		}
		return strBuilder.toString();
	}

	//base64解码使用的字节数组
	private static final byte[] BASE64_DECODE_CHARS = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6,
			7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
			29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1,
			-1 };
	/**
	 * 将指定的字符串进行base64解码
	 * @param str 待解码字符串
	 * @return base64解码后的字符串,当传入空字符串时返回null
	 */
	public static String base64Decode(String str) {
		if (JudgeUtil.isBlank(str)) return null;
		StringBuilder strBuilder = new StringBuilder();
		int i = 0, length = str.length();
		while (i < length) {
			int c1;
			do {
				c1 = BASE64_DECODE_CHARS[str.codePointAt(i++) & 0xff];
			} while (i < length && c1 == -1);
			if (c1 == -1) break;
			int c2;
			do {
				c2 = BASE64_DECODE_CHARS[str.codePointAt(i++) & 0xff];
			} while (i < length && c2 == -1);
			if (c2 == -1) break;
			strBuilder.append((char) ((c1 << 2) | ((c2 & 0x30) >> 4)));
			int c3;
			do {
				c3 = str.codePointAt(i++) & 0xff;
				if (c3 == 61) return iso2utf(strBuilder.toString());
				c3 = BASE64_DECODE_CHARS[c3];
			} while (i < length && c3 == -1);
			if (c3 == -1) break;
			strBuilder.append((char) (((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2)));
			int c4;
			do {
				c4 = str.codePointAt(i++) & 0xff;
				if (c4 == 61) return iso2utf(strBuilder.toString());
				c4 = BASE64_DECODE_CHARS[c4];
			} while (i < length && c4 == -1);
			if (c4 == -1) break;
			strBuilder.append((char) (((c3 & 0x03) << 6) | c4));
		}
		return iso2utf(strBuilder.toString());
	}
	
	public static String byte2base64(byte[] data){
		try {
			return base64Encode(new String(data,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}
	
	public static byte[] base642byte(String data){
		try {
			return base64Decode(data).getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}
	
	/**
	 * 将字符串转换为输入流
	 * @param str 待转换字符串
	 * @return 字符串转换成的输入流，当传入空字符串时返回null
	 */
	public static InputStream getInputStream(String str){
		if(JudgeUtil.isBlank(str)) return null;
		try {
			return new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}
}
